//
//  ExpandableNSFetchedResultsController.m
//  Sudoku
//
//  Created by Richard Hodgkins on 29/09/2012.
//  Copyright (c) 2012 Richard Hodgkins. All rights reserved.
//

#import "ExpandableNSFetchedResultsController.h"

@interface ExpandableNSFetchedResultsController ()

@property (nonatomic, strong) NSMutableDictionary *expandableSections;

@end

@implementation ExpandableNSFetchedResultsController

-(id)initWithFetchRequest:(NSFetchRequest *)fetchRequest managedObjectContext:(NSManagedObjectContext *)context sectionNameKeyPath:(NSString *)sectionNameKeyPath cacheName:(NSString *)name
{
    self = [super initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:sectionNameKeyPath cacheName:name];
    if (self) {
        self.expandableSections = [NSMutableDictionary dictionary];
    }
    return self;
}

-(BOOL) isSectionExpanded:(NSUInteger) section
{
    NSNumber *expanded = [self.expandableSections objectForKey:@(section)];
    return expanded ? [expanded boolValue] : NO;
}

-(BOOL) toggleSectionExpanded:(NSUInteger) section
{
    return [self setSection:section expanded:![self isSectionExpanded:section]];
}

-(BOOL) setSection:(NSUInteger) section expanded:(BOOL) isExpanded
{
    const BOOL oldValue = [self isSectionExpanded:section];
    if (oldValue != isExpanded) {
        [self.expandableSections setObject:[NSNumber numberWithBool:isExpanded] forKey:@(section)];
        return YES;
    } else {
        return NO;
    }
}

@end
